package org.longs.converter.parser;

import lombok.Getter;
import lombok.Setter;
import org.longs.bean.PalRGB;

import java.awt.*;
import java.awt.image.BufferedImage;

public class Recorder {
    @Setter
    @Getter
    private BufferedImage bufferedImage;
    @Setter
    @Getter
    private boolean interrupt = true;
    @Setter
    @Getter
    private byte[] bytes;

    @Setter
    @Getter
    private PalRGB[] palRGBs;
    @Setter
    @Getter
    private int width = 0;
    @Setter
    @Getter
    private int height = 0;
    @Setter
    @Getter
    private int offset = 0;

    @Setter
    @Getter
    private String flag;
    @Setter
    @Getter
    private int keyY;
    @Setter
    @Getter
    private int keyX;


    public int getOffsetUp() {
        return offset++;
    }


    private byte aByte;

    public byte getByte() {
        return aByte;
    }

    public int getWidthUp() {
        return width++;
    }


    public void setByte(byte aByte) {
        this.aByte = aByte;
    }


    public void loop(byte[] bytes, BufferedImage bufferedImage) {
        setBytes(bytes);
        setBufferedImage(bufferedImage);
        ParserManager singleton = ParserManager.getSingleton();
        while (isInterrupt()) {
            setByte(bytes[getOffsetUp()]);
            for (Parser parser : singleton.getContainer()) {
                if (parser.judge(getByte() & 0xFF)) {
                    parser.analysis(this, (color, record) -> {
                        if (color != null) {
                            if (record.getWidth() >= bufferedImage.getWidth()) {
                                return;
                            }
                            bufferedImage.setRGB(record.getWidthUp(), record.getHeight(), color.getRGB());
                        }
                    });
                    break;
                }
            }
            if (getByte() == 0 && getOffset() == 1 && getHeight() > 0) {
                for (int i = 0; i < bufferedImage.getWidth(); i++) {
                    if (bufferedImage.getRGB(i, getHeight() - 1) == 0) {
                        continue;
                    }
                    if (getHeight() % 2 == 0) {
                        break;
                    }
                    System.out.println(getHeight() % 2);
                    System.out.println("width:" + i + "Height:" + getHeight());
                    bufferedImage.setRGB(i, getHeight(), bufferedImage.getRGB(i, getHeight() - 1));
                }
                break;
            }
        }

        setInterrupt(true);
        setWidth(0);
        setOffset(0);
        setHeightUp();

    }

    private void setHeightUp() {
        this.height++;
    }
}
